package com.fengye.security.security.auth.ldap;

import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * @author fengyexjtu@126.com
 * @date 2022年05月24日 8:20 PM
 */

@RequiredArgsConstructor
public class LdapMultiAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
    private final LdapUserRepository ldapUserRepository;
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        // 拷贝自 org/springframework/security/authentication/dao/DaoAuthenticationProvider.java#additionalAuthenticationChecks
        if (authentication.getCredentials() == null) {
            this.logger.debug("Failed to authenticate since no credentials provided");
            throw new BadCredentialsException(this.messages
                    .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
        // String presentedPassword = authentication.getCredentials().toString();
        // if (!this.passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
        //     this.logger.debug("Failed to authenticate since password does not match stored value");
        //     throw new BadCredentialsException(this.messages
        //             .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        // }
        this.logger.info("验证通过");
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        return ldapUserRepository.findByUsernameAndPassword(username, authentication.getCredentials().toString())
                .orElseThrow(() -> new BadCredentialsException("用户名或密码错误!!!"));
    }
}
